<template>
  <el-card class="box-card">
    <el-form label-width="100">
        <el-form-item label="SPU名称">
            <el-input v-model="spuObj.spuName" placeholder="输入SPU名称"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select v-model="spuObj.tmId" placeholder="请选择你的品牌">
                <el-option v-for="item,index in allTrademark" :key="index" :label="item.tmName" :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input v-model="spuObj.description" type="textarea" placeholder="请输入SPU描述"></el-input>
        </el-form-item>
        <el-form-item label="SPU照片">
            <el-upload v-model:file-list="spuHasImg" list-type="picture-card" action="api/admin/product/fileUpload" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUpload">
                <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="preImage" alt="Preview Image" style="width:100%;height:100%;"/>
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性">
            <!-- 展示销售属性的下拉菜单 -->
            <el-select v-model="saleAttrIdAndValueName" :placeholder="unSelectSaleAttr.length?`还未选择${unSelectSaleAttr.length}个`:'没有可选择的属性'">
                <el-option v-for="item,index in unSelectSaleAttr" :key="index" :label="item.name" :value="`${item.id}:${item.name}`"></el-option>
            </el-select>
            <el-button :disabled="saleAttrIdAndValueName?false:true" type="primary" size="default" icon="plus" style="margin-left:10px;" @click="addSaleAttr">添加属性</el-button>
            <!-- 展示销售属性与属性值的table -->
            <el-table :data="spuHasSaleAttr" border style="width:100%;margin:10px 0;">
                <el-table-column label="序号" type="index" width="80"></el-table-column>
                <el-table-column prop="saleAttrName" label="销售属性名称" width="150"></el-table-column>
                <el-table-column label="销售属性值">
                    <template #="{row,$index}">
                        <el-tag v-for="item,index in row.spuSaleAttrValueList" :key="row.id" @close="row.spuSaleAttrValueList.splice(index,1)" closable style="margin:0 10px;">{{item.saleAttrValueName}}</el-tag>
                        <el-input v-if="row.flag == true" v-model="row.saleAttrValue" @blur="toLook(row)" placeholder="请输入" size="small" style="width:100px;"></el-input>
                        <el-button v-else @click="toEdit(row)" type="primary" size="small" icon="plus"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #="{row,$index}">
                        <el-button type="danger" size="small" icon="delete" @click="spuHasSaleAttr.splice($index,1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <!-- 按钮部分 -->
        <el-form-item label="">
            <el-button type="primary" @click="saveAddSpu">保存</el-button>
            <el-button type="info" @click="cancelAddSpu">取消</el-button>
        </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ElCard, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElUpload, ElIcon, ElDialog, ElButton, ElTable, ElTableColumn, ElTag, ElMessage } from "element-plus";
import { Plus } from '@element-plus/icons-vue';
//@ts-ignore,请求函数
import { reqAllTrademark, reqSpuImageList, reqSpuHasSaleAttr, reqAllSaleAttr, reqUpdateSpu, reqAddSpu } from "@/api/product/index.ts";
//@ts-ignore
import type { Trademark, SpuHasImg, SaleAttrResponseData, hasSaleAttrResponseData, spuImg, saleAttrValue, HasSaleAttr, spuDataParams} from "@/api/product/type.ts";
import { defineEmits, defineExpose, reactive, ref, computed } from "vue";
const emit = defineEmits(['changeScene']);

//已有spu进行修改数据收集
//存储spu对象
let spuObj = ref<spuDataParams>({
    category3Id:0,
    spuName:"",
    description:"",
    tmId:null,
    spuImageList:[],
    spuSaleAttrList:[]
});
//全部品牌
let allTrademark = ref<Trademark[]>([]);
//当前spu下已有的商品图片
let spuHasImg = ref<spuImg[]>([]);
//已有的spu销售属性type: saleAttrValue[]
let spuHasSaleAttr = ref<any>([]);
//全部的销售属性
let allSaleAttr = ref<HasSaleAttr[]>([]);
//收集还未选择的属性的名字及id，及属性值的名字
let saleAttrIdAndValueName = ref<string>("");

//计算出当前spu还未拥有的销售属性
let unSelectSaleAttr = computed(()=>{
    let unSelect = allSaleAttr.value.filter(item => {
        return spuHasSaleAttr.value.every(ele => {
            return item.name != ele.saleAttrName;
        })
    })
    return unSelect;
})

//添加属性按钮
const addSaleAttr = () => {
    const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':');
    //准备一个新的销售属性对象，存储再已有的spu销售属性中
    let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList:[]
    }
    spuHasSaleAttr.value.push(obj);
    saleAttrIdAndValueName.value = "";
}
//属性值添加按钮事件
const toEdit = (row) => {
    row.flag = true;
    row.saleAttrValue = "";
}
//属性值添加input框的blur事件
const toLook = (row) => {
    if(row.saleAttrValue.trim() == ""){
        return ElMessage({type:"warning",message:"属性值不能为空!"});
    }
    const {baseSaleAttrId,saleAttrValue} = row;
    if(row.spuSaleAttrValueList.findIndex(item => item.saleAttrValueName == saleAttrValue) !== -1){
        return ElMessage({type:"warning",message:"属性值不能重复"});
    }
    let obj = {baseSaleAttrId,saleAttrValueName:saleAttrValue};
    row.spuSaleAttrValueList.push(obj);
    row.flag = false;
}

//Spu的保存与取消按钮
const saveAddSpu = async () => {
    //整理请求参数
    spuObj.value.spuImageList = spuHasImg.value.map(item => {
        return {
            imgName:item.name,
            imgUrl:(item.response && item.response.data) || item.url,
        }
    })
    spuObj.value.spuSaleAttrList = spuHasSaleAttr.value;
    //发请求更新或者添加SPU
    if(spuObj.value.id){
        //更新spu
        let res:any = await reqUpdateSpu(spuObj.value);
        if(res.code == 200){
            ElMessage({type:"success",message:"SPU更新成功!"});
            // console.log("spu更新api成功",res);
        }
    } else {
        //添加spu
        let res:any = await reqAddSpu(spuObj.value);
        if(res.code == 200){
            ElMessage({type:"success",message:"SPU添加成功!"});
            console.log("spu添加api成功",res);
        }
    }
    //切换场景
    cancelAddSpu();
}
const cancelAddSpu = () => {
    emit("changeScene",0);
    //清除数据
    spuObj.value = {
        category3Id:0,
        spuName:"",
        description:"",
        tmId:null,
        spuImageList:[],
        spuSaleAttrList:[]
    }
    spuHasImg.value = [];
    spuHasSaleAttr.value = [];
    saleAttrIdAndValueName.value = "";
}

//图片上传组件的的方法与相关属性
let dialogVisible = ref<boolean>(false);  //照片墙的对话框
let preImage = ref(null);
//预览图片的回调
const handlePictureCardPreview = (file:any) => {
    dialogVisible.value = true;
    preImage.value = file.url
}
//照片墙移除照片事件
const handleRemove = () => {}
//图片上传前的回调
const beforeUpload = (file:any) => {}

//本组件的方法，对外暴露，供父组件调用，传递数据获取已有spu全部数据
//添加spu
const addSpu = async (category3Id:number) => {
    spuObj.value.category3Id = category3Id;
    //发请求获取所有品牌
    let res1:Trademark = await reqAllTrademark();
    if(res1.code == 200){
        allTrademark.value = res1.data;
        // console.log("全部品牌数据api成功",res1);
    }
    //发请求获取所有销售属性
    let res4:hasSaleAttrResponseData = await reqAllSaleAttr();
    if(res4.code == 200){
        allSaleAttr.value = res4.data;
        // console.log("全部销售属性api成功",res4);
    }
}
//更新spu
const getSpuData = async (spuData) => {
    spuObj.value = spuData;
    //spuData即为父组件传递过来的已有的spu对象，但不完整
    //获取全部品牌数据
    let res1:Trademark = await reqAllTrademark();
    if(res1.code == 200){
        allTrademark.value = res1.data;
        // console.log("全部品牌数据api成功",res1);
    }
    //获取某一个品牌下的全部售卖商品的图片
    let res2:SpuHasImg = await reqSpuImageList(spuData.id);
    if(res2.code == 200){
        spuHasImg.value = res2.data.map(item => {
            return{
                name:item.imgName,
                url:item.imgUrl
            }
        })
        // console.log("当前品牌下的售卖商品图片api成功",res2);
    }
    //获取已有的spu销售属性的数据
    let res3:SaleAttrResponseData = await reqSpuHasSaleAttr(spuData.id);
    if(res3.code == 200){
        spuHasSaleAttr.value = res3.data;
        // console.log("当前spu销售属性数据api成功",res3);
    }
    //获取全部销售属性
    let res4:hasSaleAttrResponseData = await reqAllSaleAttr();
    if(res4.code == 200){
        allSaleAttr.value = res4.data;
        // console.log("全部销售属性api成功",res4);
    }
}

//对外暴露属性或方法
defineExpose({
    getSpuData,
    addSpu
})
</script>
<script lang="ts">
export default {
    name:"SpuForm"
}
</script>

<style>

</style>